package com.cgwx.systemservice.controller;

import com.cgwx.commonutils.JwtUtils;
import com.cgwx.commonutils.MD5;
import com.cgwx.commonutils.result.SysResult;
import com.cgwx.servicebase.exceptionhandler.MyException;
import com.cgwx.springsecurity.entity.SysUser;
import com.cgwx.springsecurity.entity.LoginVo;
import com.cgwx.systemservice.service.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author GaoWei
 * @Date 2023/10/18 - 15:30
 */

@Api(tags = "登录管理")
@RestController
@RequestMapping("/system/login")
@CrossOrigin
public class LoginController {

    @Autowired
    private SysUserService sysUserService;

//    login方法
    @ApiOperation(value = "登录检查方法")
    @PostMapping("user/login")
    public SysResult login(
            @ApiParam(name = "loginVo", value = "登录VO")
            @RequestBody LoginVo loginVo) {
//        根据用户名称查询数据库
        SysUser sysUser = sysUserService.getUserInfoByUserName(loginVo.getUsername());
        if(sysUser == null){
            throw new MyException(20001,"用户不存在");
        }
//        判断密码
        if(!MD5.encrypt(loginVo.getPassword()).equals(sysUser.getPassword())){
//            密码不一致
            throw new MyException(20001,"密码不正确");
        }
        if(sysUser.getStatus() == 0){
//            用户不可用
            throw new MyException(20001,"用户已被禁用");
        }
//        全部检查通过后，生成token字符串
        String token = JwtUtils.createToken(sysUser.getId(), sysUser.getUsername());
//        返回数据
        Map<String,Object> map = new HashMap<>();
        map.put("token",token);
        return SysResult.ok(map);
    }

    //    info方法
    @ApiOperation(value = "登录后返回信息，请求头中含token")
    @GetMapping("user/info")
    public SysResult info(
            @ApiParam(name = "request", value = "请求")
            HttpServletRequest request) {
//        获取请求头token字符串
        String token = request.getHeader("token");
//        从token中获取用户名称，用户id
        String username = JwtUtils.getUsername(token);
//        根据用户名称获取用户信息（基本信息，菜单权限，按钮权限数据）
        Map<String,Object> infoMap = sysUserService.getUserInfo(username);
        return SysResult.ok(infoMap);
    }
}
